# -*- coding: utf-8 -*-
import sys

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import talib
from matplotlib import ticker

from api.oksHttp import getKData
from bean.MarketData import MarketData

# help(ts.get_k_data) 了解参数
df = getKData("ETH-USDT", 1711768274813, 1711472234000, "15m", 329)
if len(df) < 30:
    print(" len(df) <30 ")
    sys.exit(2)

kdataList=[]
for item in df:
    markData = MarketData(item[0], item[1], item[2], item[3], item[4], item[5], item[6], item[7], item[8])
    kdataList.append(markData)

 # 取收盘价
close_price_list = [data.close_price for data in kdataList]
close_price_array = np.array(close_price_list, dtype='float')
# 计算布林线
upper, middle, lower = talib.BBANDS(close_price_array, timeperiod=20, nbdevup=2, nbdevdn=2, matype=0)
# 为每个MarketData对象设置布林带值
for i, data in enumerate(kdataList):
    if np.isnan(upper[i]):
        # 如果是前20个数据点或者upperband是nan，则跳过设置布林带
        continue
    # 使用对应索引的布林带值设置
    data.set_bollinger_bands(upper[i], middle[i], lower[i])

# 计算RSI
rsi = talib.RSI(close_price_array, timeperiod=14)

# 计算MACD
macd, macdsignal, macdhist = talib.MACD(close_price_array, fastperiod=12, slowperiod=26, signalperiod=9)
# 提取收盘价和布林线数据
close_prices = [float(data.close_price) for data in kdataList]
upper_bands = [data.upperband for data in kdataList]
middle_bands = [data.middleband for data in kdataList]
lower_bands = [data.lowerband for data in kdataList]

# # 绘制图表
# plt.figure(figsize=(15, 7))
# plt.plot(close_prices, label='Close Prices', color='blue')
# plt.plot(upper_bands, label='Upper Band', color='red', linestyle='--')
# plt.plot(middle_bands, label='Middle Band', color='green')
# plt.plot(lower_bands, label='Lower Band', color='red', linestyle='--')
#
# plt.title('Bollinger Bands')
# plt.xlabel('Time')
# plt.ylabel('Price')
# plt.legend(loc='best')
# plt.show()
# 假设您已经有了这些数据
upper_bands = np.array(upper_bands)
middle_bands = np.array(middle_bands)
lower_bands = np.array(lower_bands)

# 计算布林带宽度
band_width = upper_bands - lower_bands

# 设定阈值，这个阈值可能需要您根据数据自行调整
threshold = np.nanmean(band_width) * 0.6  # 举例：宽度小于平均宽度的一半

# 找出宽度小于阈值的区间
narrow_band = band_width < threshold

# 绘制布林带
plt.figure(figsize=(15, 7))
plt.plot(close_prices, label='Close Prices', color='blue')
plt.plot(upper_bands, label='Upper Band', color='red', linestyle='--')
plt.plot(middle_bands, label='Middle Band', color='green')
plt.plot(lower_bands, label='Lower Band', color='red', linestyle='--')
# 标记窄带区域
# 设置x轴的主刻度定位器为每隔10个点一个刻度
ax = plt.gca()
ax.xaxis.set_major_locator(ticker.MultipleLocator(10))  # 设置x轴刻度间隔
ax.yaxis.set_major_locator(ticker.MaxNLocator(nbins=10))  # 自动选择y轴刻度间隔
plt.grid(True, which='major', axis='x', linestyle='--', alpha=0.7)

plt.fill_between(range(len(close_prices)), lower_bands, upper_bands, where=narrow_band, color='grey', alpha=0.5)
plt.title('Bollinger Bands with Stable Zone Highlighted')
plt.xlabel('Time')
plt.ylabel('Price')
plt.legend()

# 新的图形用于绘制RSI
plt.figure(figsize=(15, 7))
plt.plot(rsi, color='orange', label='RSI')
plt.axhline(70, linestyle='--', color='red', label='Overbought (70)')
plt.axhline(30, linestyle='--', color='green', label='Oversold (30)')
plt.title('RSI Chart')
# 设置x轴的主刻度定位器为每隔10个点一个刻度
ax = plt.gca()
ax.xaxis.set_major_locator(ticker.MultipleLocator(10))  # 设置x轴刻度间隔
ax.yaxis.set_major_locator(ticker.MaxNLocator(nbins=10))  # 自动选择y轴刻度间隔
plt.grid(True, which='major', axis='x', linestyle='--', alpha=0.7)

plt.legend()
plt.show()

# 绘制图表
plt.figure(figsize=(15, 7))
plt.plot(macd, label='MACD', color='blue')
plt.plot(macdsignal, label='MACD Signal', color='red')
plt.bar(range(len(macdhist)), macdhist, label='MACD Histogram', color='grey')
plt.legend()
# 设置x轴的主刻度定位器为每隔10个点一个刻度
ax = plt.gca()
ax.xaxis.set_major_locator(ticker.MultipleLocator(10))  # 设置x轴刻度间隔
ax.yaxis.set_major_locator(ticker.MaxNLocator(nbins=10))  # 自动选择y轴刻度间隔
plt.grid(True, which='major', axis='x', linestyle='--', alpha=0.7)

plt.title('MACD')
plt.show()